<?php
/**
 *
 */
namespace App\Service;

use App\Model\Account;
use App\Model\UserBind;
use App\ServiceInterface;

class BindService implements ServiceInterface
{
    private $_server;

    private $_fd;

    private $_data;

    /**
     * BindService constructor.
     * @param null $server
     * @param int $fd
     * @param array $data
     */
    public function __construct($server=null,int $fd=0, array $data=[])
    {
        $this->_server = $server;
        $this->_fd     = $fd;
        $this->_data   = $data;
    }

    /**
     * 参数校验
     * @return string
     */
    public function check():string
    {
        if (!isset($this->_data['account']) || intval($this->_data['account']) <= 0)
        {
            return 'account is null';
        }
        if (!isset($this->_data['appid']) || intval($this->_data['appid']) <= 0)
        {
            return 'appid is null';
        }

        return '';
    }

    /**
     * 具体逻辑
     * @return array
     */
    public function init():array
    {
        try {
            if ($check_msg = $this->check())
                throw new \Exception($check_msg);

            $this->_data['fd'] = $this->_fd;
            $login_msg = UserBind::updateUser($this->_data['appid'],$this->_data);
            if (!is_array($login_msg))
                throw new \Exception($login_msg);


            $this->_data['message'] = '';

            unset($this->_data['appid']);

            return [0, 'success', $this->_data];
        }catch (\Exception $e){
            return [-1, $e->getMessage(), $this->_data];
        }
    }


    /**
     * 清空用户信息和msg(先不考虑）,以防fd影响
     * @param $fd
     * @return bool
     */
    public function unBind($fd){
        try{
            UserBind::where(['fd'=>$fd])->update(['fd'=>0]);
            return true;
        }catch(\Exception $e){
            echo 'pdoerror '.$e->getMessage().' file is '.$e->getFile().' line on '.$e->getLine();
            return false;
        }

    }

    /**
     * 连接校验
     * @param $appid
     * @return string
     */
    public function authCheck($appid){
        if (empty($appid)) {
            return 'appid is null';
        }

        try{
            $info = Account::select(['appid','appkey'])
                ->where(['appid'=>$appid])
                ->first();
            if (!$info) {
                throw new \Exception('认证失败');
            }
            return '';
        }catch(\Exception $e){
            return $e->getMessage();
        }
    }

}